//
//  setupViewController.m
//  ioschishan
//
//  Created by 千翼网络科技 on 2017/7/14.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "setupViewController.h"
#import "setupTableViewCell.h"
#import "welcomeViewController.h"
#import "safeViewController.h"
#import "myHelpViewController.h"
#import "opinionViewController.h"
#import "aboutUsViewController.h"

@interface setupViewController ()<UITableViewDelegate , UITableViewDataSource>{
    
    NSArray *titleArray;
    NSString *cacheStr;
}

@property(nonatomic,strong) NSMutableArray *dataArray;
@property(nonatomic,strong) NSMutableDictionary *dataDic;
@property(nonatomic,strong) UITableView *helpTableView;
@property(nonatomic,strong) UILabel *moneyNumLabel;

@end

@implementation setupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
}

#pragma mark ------------------ init -------------------

- (void)initView{
    
    self.title = @"设置";
    titleArray = @[@"账号与安全",@"消息通知",@"清理缓存",@"帮助",@"意见与反馈",@"关于我们",];
    
    _helpTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), scrHeight() - 64)];
    _helpTableView.backgroundColor = getColor(@"ffffff");
    _helpTableView.delegate = self;
    _helpTableView.dataSource = self;
    _helpTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_helpTableView];
    
    UIView *threadView = [[UIView alloc]initWithFrame:CGRectMake(0, screenScale(1), scrWidth(), screenScale(0.7))];
    threadView.backgroundColor = getColor(@"cccccc");
    [self.view addSubview:threadView];
    
    UIButton *exitBtn = [ConfigXp buttonWithFrame:CGRectZero
                                            title:@"退出登录"
                                       titleColor:getColor(@"4a4a4a")
                                             font:get4sFont(14)
                                  backgroundColor:getColor(@"ffffff")
                                            image:nil];
    [exitBtn addTarget:self action:@selector(exitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitBtn];
    [exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.right.mas_equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(screenScale(55));
    }];
    
    UIView *bottomThreadView = [[UIView alloc]init];
    bottomThreadView.backgroundColor = getColor(@"cccccc");
    [self.view addSubview:bottomThreadView];
    [bottomThreadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(exitBtn.mas_top).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.right.mas_equalTo(self.view).with.offset(0);
        make.height.mas_equalTo(screenScale(0.5));
    }];
}

#pragma mark -------------------- click ----------------------

- (void)exitBtnClick{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"    确定退出？" preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        
        welcomeViewController *loginCtrl = [[welcomeViewController alloc] init];
        UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
        self.view.window.rootViewController = navCtrl;
        self.view.window.backgroundColor = [UIColor whiteColor];
        [self.view.window makeKeyAndVisible];
        
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alert addAction:action];
    [alert addAction:cancel];
    [self showDetailViewController:alert sender:nil];
    
//    welcomeViewController* vc = [[welcomeViewController alloc]init];
//    NSMutableArray *array = [self.navigationController.viewControllers mutableCopy];
//    [array removeObject:self];
//    [array addObject:vc];
//    [self.navigationController setViewControllers:array animated:YES];
    
}

-(void)switchAction:(id)sender{
    
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        
        NSLog(@"1");
        
    }else {
        
        NSLog(@"2");
        
    }
}

#pragma mark -------------------- cache ----------------------

//首先计算单个文件的大小

- (long long)fileSizeAtPath:(NSString *)filePath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error : nil] fileSize];
        
    }
    
    return 0 ;
    
}

//遍历文件夹获得文件夹大小，返回多少M

- (float)folderSizeAtPath:(NSString *)folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}

// 显示缓存大小

- (float)filePath{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    return [self folderSizeAtPath:cachPath];
    
}

// 清理缓存

- (void)clearFile{
    
    NSString * cachPath = [NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    
    NSArray * files = [[NSFileManager defaultManager] subpathsAtPath :cachPath];
    
    NSLog (@"cachpath = %@" , cachPath);
    
    for (NSString *p in files) {
        
        NSError *error = nil ;
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath :path]){
            
            [[NSFileManager defaultManager] removeItemAtPath :path error :&error];
            
        }
        
    }
    
    [self performSelectorOnMainThread:@selector(clearCachSuccess) withObject:nil waitUntilDone:YES];
    
}

- (void)clearCachSuccess{
    
    NSLog(@"清理成功");
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message: @"缓存清理完毕" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    [alertView show];
    cacheStr = nil;
    
    [_helpTableView reloadData];//清理完之后重新导入数据
    
}

#pragma mark -------------------- tableView ----------------------

#pragma mark --- UITableViewDelegate ---

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return screenScale(49);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        safeViewController *vc = [[safeViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row == 1){
    
        
        
    }else if (indexPath.row == 2){
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定清除缓存？" preferredStyle:(UIAlertControllerStyleAlert)];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
            
            [self clearFile];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        [alert addAction:action];
        [alert addAction:cancel];
        [self showDetailViewController:alert sender:nil];
        
    }else if (indexPath.row == 3){
        
        myHelpViewController *vc = [[myHelpViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row == 4){
        
        opinionViewController *vc = [[opinionViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.row == 5){
        
        aboutUsViewController *vc = [[aboutUsViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}

#pragma mark --- UITableViewDataSource ---

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView registerClass:[setupTableViewCell class] forCellReuseIdentifier:@"identifier"];
    setupTableViewCell *cell = (setupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.nameLable.text = titleArray[indexPath.row];
    [cell.switchButton addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    
    if (indexPath.row == 0) {
        
        cell.statusLable.hidden = NO;
        
    }else if (indexPath.row == 2){
    
        cell.statusLable.hidden = NO;
        cell.statusLable.text = [NSString stringWithFormat : @"%.2fM" , [self filePath]];
        
        
    }else if (indexPath.row == 1){
    
        cell.switchButton.hidden = NO;
//        [cell.switchButton setOn:NO];
        
    }
    
    return cell;
}

@end
